import { ref } from 'vue'
import { adapter, request } from '@/request'
import { industryByGet } from '@/core/api/order'
import type { RequestWrapper } from '@/core/interfaces/common'
import type { Industry } from '@/core/interfaces/industry'

export function linkIndustryParent(industry: Industry) {
  const result: Industry['id'][] = [industry.id]
  let condition = industry?.parent
  while (condition) {
    result.unshift(condition.id)
    condition = condition?.parent ?? undefined
  }

  return result
}

export function getIndustryTree(items: Industry[]) {
  const tree: Industry[] = [] // 存放结果集

  const diagram = items.reduce<Record<Industry['code'], Industry>>((p, n) => {
    p[n.code] = {
      ...n,
      children: []
    }
    return p
  }, {})

  items.forEach((d) => {
    const treeItem = diagram[d.code]
    if (d.fatherCode === 0) {
      tree.push(treeItem)
    } else {
      if (!diagram[d.fatherCode]) {
        diagram[d.fatherCode].children = []
      }
      treeItem.parent = diagram[d.fatherCode]
      diagram[d.fatherCode].children?.push({
        ...treeItem,
        parent: diagram[d.fatherCode]
      })
    }
  })

  return {
    tree,
    diagram
  }
}

export default function getIndustryList() {
  const service = adapter<RequestWrapper<Industry[]>>(request)
  const loading = ref(false)
  const response = ref<Industry[]>([])

  const fetch = () => {
    const { url, method } = industryByGet()
    loading.value = true

    return service({
      config: {
        url,
        method
      },
      callback: (res) => {
        response.value = res.data.data.map((item) => {
          return {
            ...item,
            label: item.name,
            value: item.id
          }
        })
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
